<template>
  <p-card :bordered="false" class="peopleInfo">
    <!-- 查询区域 -->
    <div
      class="table-page-search-wrapper"
      v-if="queryParamArr && queryParamArr.length > 0"
    >
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col
            :xl="6"
            :lg="7"
            :md="8"
            :sm="24"
            v-for="(item, index) in queryParamArr"
            :key="index"
          >
            <p-form-item :label="item.label">
              <p-input
                :placeholder="item.placeholder"
                v-model="item.value"
              ></p-input>
            </p-form-item>
          </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span
              style="float: left; overflow: hidden"
              class="table-page-search-submitButtons"
            >
              <p-button type="primary" @click="searchQuery" icon="search"
                >查询</p-button
              >
              <p-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
                >重置</p-button
              >
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>

    <slot name="btn"></slot>

    <!-- 高级查询区域 -->
    <j-super-query
      v-if="superQueryFieldList && superQueryFieldList.length > 0"
      :fieldList="superQueryFieldList"
      ref="superQueryModal"
      @handleSuperQuery="handleSuperQuery"
      style="padding-bottom:10px; margin-right: 10px"
    ></j-super-query>

    <p-button type="primary" v-if="isShowDeleteBatch" :disabled = 'selectedRowKeys.length == 0' @click="handleDeleteBatch" >批量删除</p-button>


    <!-- table区域-begin -->
    <div class="peopleInfo-table" >
      <div v-if="isShowToolBar" class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float: right">
          <a @click="handleExportXls('关键字段信息')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a> <p-icon type="import" />导入 </a>
          </p-upload>
          <p-divider type="vertical" />
          <a @click="loadData()"> <p-icon type="sync" />刷新 </a>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12">
                        <p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a> <p-icon type="setting" />自定义列 </a>
          </p-popover>
        </span>
      </div>

        <!-- :scroll="tableScroll" -->
        <!-- :scroll="{ x: 1000, y: 300 }" -->

      <p-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="
          isShowRowSelection
            ? {
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                type: rowSelectionType,
              }
            : null
        "
        @change="handleTableChange"
      >

        <template v-if="isUseStatusTemp" slot="status" slot-scope="text, record">
          <p-switch
            size="small"
            v-model="record.status"
            @change="onSwitchChange(record)"
          />
        </template>

        <template slot="url" slot-scope="text, record">
          <a :href="text" target="_blank">下载附件</a>
        </template>

        <template slot="action" slot-scope="text, record">
          <slot name="action" :record="record">
            <a @click="handleEdit(record)">编辑</a>
            <p-divider type="vertical" />
            <p-dropdown>
              <a class="ant-dropdown-link">
                更多
                <p-icon type="down" />
              </a>
              <p-menu slot="overlay">
                <p-menu-item>
                  <p-popconfirm
                    title="确定删除吗?"
                    @confirm="() => handleDelete(record.id)"
                  >
                    <a>删除</a>
                  </p-popconfirm>
                </p-menu-item>
              </p-menu>
            </p-dropdown>
          </slot>
        </template>
      </p-table>
    </div>
  </p-card>
</template>

<script type="text/javascript">
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { postAction, getAction, deleteAction, putAction } from "@/api/manage";
import { filterObj } from "@/utils/util";

export default {
  name: "RenderTable",
  props: {
    // 高级查询
    superQueryFieldList: {
      type: Array,
      // required: true,
      default: [],
    },
    // 选择款类型
    rowSelectionType: {
      type: String,
      // required: true,
      default: "",
    },
    // 是否有选择框
    isShowRowSelection: {
      type: Boolean,
      default: false,
    },
    // 默认的查询参数
    defaultQueryParam: {
      type: Object,
      // required: true,
      default: {},
    },
    // 查询的数组
    queryParamArr: {
      type: Array,
      default: [],
    },
    // 列定义
    defColumns: {
      type: Array,
    },
    // 请求接口地址
    url: {
      type: Object,
    },
    // 获取列表时默认的请求参数
    defaultParams: {
      type: Object,
      default: {}
    },
    // 是否显示工具栏
    isShowToolBar: {
      type: Boolean,
      default: true
    },
    // 是否显示批量删除
    isShowDeleteBatch: {
      type: Boolean,
      default: false
    }, 

    // 是否使用状态模板
    isUseStatusTemp: {
      type: true,
      default: false
    }, 

  },
  data() {
    return {
      queryParam: {},
      originQueryParam: {},
      originQueryParamArr: [],
      selectedRowKeys: [],
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: "",
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "50"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      dataSource: [],
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
    };
  },
  computed: {
    tableScroll() {
      if (this.columns.length > 13) {
        return { x: this.columns.length * 150 - 450 };
        // return { x: 1550 };
      }
    },
  },

  watch: {
    queryParamArr: {
      handler(newName, oldName) {
        newName.forEach((ele) => {
          this.$set(this.queryParam, ele.key, ele.value);
        });
      },
      deep: true,
      immediate: true,
    },
  },

  mounted() {
    this.originQueryParamArr = JSON.parse(JSON.stringify(this.queryParamArr))
    this.initColumns();
    this.setDefColumns();
    this.loadData(1);
  },
  methods: {
    // 初始化 tabe的Columns
    initColumns() {
      let allSettingColumns = [];
      this.defColumns.forEach(function (item, i, array) {
        allSettingColumns.push(item.dataIndex);
      });
      this.settingColumns = allSettingColumns;
      this.columns = this.defColumns;
    },

    //列设置更改事件
    onColSettingsChange(checkedValues) {
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },

    // table 的分页事件
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = sorter.order == "ascend" ? "asc" : "desc";
      }
      //筛选 多选
      Object.keys(filters).map((key) => {
        let k = key;
        let data = [];
        filters[k].forEach((item, index) => {
          data.push(item);
        });
        //表头筛选表头带的value值是字典的value，接口筛选的时候需要的是字典的key 这边把表头携带的_deicText  默认去掉
        if (k.indexOf("_dictText") > -1) {
          k = k.replace("_dictText", "");
        }
        this.queryParam[k] = data.toString("");
      });
      this.ipagination = pagination;
      this.loadData();
    },
    // 设置table的 columns
    setDefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1;
        this.columns.forEach((item, index) => {
          item["width"] = 130;
        });
        this.columns[arrLength]["fixed"] = "right";
        this.columns[0]["fixed"] = "left";
        this.columns[1]["fixed"] = "left";
      }
    },
    // 查询
    searchQuery() {
      this.loadData(1);
    },
    // 重置查询
    searchReset() {
      this.queryParamArr = JSON.parse(JSON.stringify(this.originQueryParamArr))
      this.$nextTick(()=> {
        this.loadData(1);
      }) 
    },
    //高级查询方法
    handleSuperQuery(arg) {
      console.log(arg);
      if (!arg) {
        this.superQueryParams = "";
        this.superQueryFlag = false;
      } else {
        this.superQueryFlag = true;
        this.superQueryParams = JSON.stringify(arg);
      }
      this.loadData();
    },
    // 获取查询条件
    getQueryParams() {
      let sqp = {};
      if (this.superQueryParams) {
        sqp["superQueryParams"] = encodeURI(this.superQueryParams);
      }
      var param = Object.assign(sqp, this.queryParam, this.defaultQueryParam);
      param.pageNo = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    // table选中改变
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
      this.$emit("onSelectChange", selectionRows);
    },
    // 清除table选中
    onClearSelected() {
      this.onSelectChange([], [])
    },
    // 查询列表
    loadData(pageIndex) {
      if (pageIndex === 1) {
        this.ipagination.pageIndex = 1;
      }
      this.onClearSelected();
      let params = this.getQueryParams(); //查询条件
      Object.assign(params, this.defaultParams)
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records.map(ele => {
            if( ele.status && (ele.status == 0 || ele.status == 1) && this.isUseStatusTemp){
              ele.status = ele.status== 0 ? false : true
            }
            return ele
          });
          this.ipagination.total = res.data.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.msg);
        }
        this.$nextTick(() => {
          this.loading = false;
        });
      });
    },
    // 编辑
    handleEdit(record) {
      this.$emit("handleEdit", record);
    },

    // 提交审批
    handleSubmit(record) {
      this.$emit("handleSubmit", record);
    },

    // 删除
    handleDelete(id) {
      deleteAction(this.url.delete + "/" + id).then((res) => {
        if (res.success) {
          this.loadData();
        }
      });
    },

    // 批量删除
    handleDeleteBatch(){
      const idStr = this.selectedRowKeys.join(',')
      deleteAction(this.url.delete + "/" + idStr).then((res) => {
        if (res.success) {
          this.loadData();
        }
      });      
    },

    // 修改状态
    onSwitchChange(record) {
      console.log(record);
      const params = {
        status: record.status ? 1 : 0,
        id: record.id,
      };
      postAction(this.url.editStatus, params).then((res) => {
        if (res.success) {
          this.$message.success("修改状态成功!");
        } else {
          this.$message.error("修改状态失败!");
          record.status = !record.status;
        }
      });
    },
  },
  components: {
    JSuperQuery,
  },
};
</script>

<style lang="less" scoped>
</style>


